<template>
    <a-drawer
      title="发布设置"
      :visible="visible"
      :width="600"
      @close="onClose"
      :destroyOnClose="true"
      :keyboard="false"
      :maskClosable="true"
      :get-container="() => parentDom"
      :wrap-style="{ position: 'absolute',right:0 }"
      :body-style="{ padding: '0', height: 'calc( 100% - 55px )' }"
    >
      <div class="list-wrap">
        <div class="left-area">
          <div class="left-header">
            <SettingOutlined class="mb-5 text-20" />
            <span>选择记忆项</span>
          </div>
          <div class="left-list">
            <template v-for="(item,key) of memory_tab_accounts_obj" :key="key">
              <template v-if="item.checkedAccountIds && item.checkedAccountIds.length">
                  <div class="left-item" :class="active_memory_tab==key?'active_memory_tab':''"   @click="memoryTabChange(key)">
                    <img :src="item.image" class="left-item-img">
                    <CloseCircleOutlined class="choose-item-close" @click.stop="delAllChooseAccount(key)" />
                  </div>
              </template>
            </template>
          </div>
        </div>
        <div class="right-area beauty-scroller-bar">
            <a-form :model="formRef" layout="vertical" >
              <a-form-item label="账号" required>
                <div class="choose-list">
                  <div class="choose-item" v-for="item in chooseAccounts" :key="item.id">
                    <CloseCircleOutlined class="choose-item-close" @click="delChooseAccount(item.id)" />
                    <div class="account-avatar-wrapper" :class="getCheckedAccountClass(item.id)">
                      <a-tooltip>
                        <template #title>{{ item.nickname }}</template>
                        <img :src="item.avatar" class="account-avatar">
                      </a-tooltip>
                    </div>
                  </div>
                  <PlusCircleOutlined class="add-btn" @click="chooseAccont" />
                </div>
            </a-form-item>
        
          <component :is="active_memory_tab"   :content="formData"></component>
    
        </a-form>
        </div>
      </div>
      <div class="footer">
        <a-button size="small"  @click="onClose">取消</a-button>
        <a-button type="primary" class="mx-10" @click="submit">确定</a-button>
      </div>
 
    <addArticlePublish :visible="accountVisible" @handleOk="ok" @onClose="()=>{accountVisible=false}" :account="memory_tab_accounts_obj"></addArticlePublish>
    </a-drawer>
  </template>
  
  <script>
  import { defineComponent, watch, computed, reactive, toRefs, toRaw,watchEffect } from "vue";
  import { Form, message, TreeSelect } from "ant-design-vue";
  import request from "../../common/utils/request";
  import store from "../../store/index";
  import utils from "../../common/utils/utils";
  import { SettingOutlined,PlusOutlined ,PlusCircleOutlined,CloseCircleOutlined} from "@ant-design/icons-vue";
  import moment from "moment";
import { nextTick } from "vue";
import RedBookForm from "./forms/RedBookForm.vue";
import addArticlePublish from "./addArticlePublish.vue";
import _ from 'lodash'
  export default defineComponent({
    name: "EditUser",
    components: { 
      PlusOutlined,
      SettingOutlined,
      PlusCircleOutlined,
      CloseCircleOutlined,
      'xiaohongshu':RedBookForm,
      addArticlePublish
    },
    props: {
      visible: {
        type: Boolean,
        default: false,
      },
      parentDom: {
        type: Object,
        default: null,
      },
      content: {
        type:String,
        default:''
      }
    },
    setup(props, context) {
      const state = reactive({
        formData:{},
          currentAccountId:'',
            forms:{
              xiaohongshu:[
                {key:'title',value:''},
                {key:'cover_img',value:[]},
                {key:'is_private',value:0},
                {key:'fix_at',value:''},
              ],
              douyin:[
                {key:'title',value:''},
                {key:'cover_img',value:[]},
                {key:'is_private',value:0},
                {key:'fix_at',value:''},
              ],
              weibo:[
                {key:'title',value:''},
                {key:'cover_img',value:[]},
                {key:'is_private',value:0},
                {key:'fix_at',value:''},
              ],
            },
            memory_tab_accounts_obj:null,
            active_memory_tab:'',
             memoryTabList:[], 
             chooseAccounts:[],
              confrim_tabs_accounts_obj:{},
              tabs_accounts_obj:{},
              currentTabId:'',
              groupAccountList:[],
              tabList:[],
              groupList:[],
              allChecked:false,
              publishTime:'',
              chooseAccountIds:[],
              checkedAccountIds:[],
              accountList:[],
              accountVisible:false,
              list: [],
              fileList:[],
          });

          // const formData = computed(()=>{
          //   let obj = state.memory_tab_accounts_obj[state.active_memory_tab]
          //   console.log(obj,'xxxxxxxxxxxxx');
          //   if(obj){
          //    console.log(222222222222);
          //     if(obj.children.length>0){
          //       console.log(obj,'objobj');
          //       console.log(obj.current_account_id,'obj.current_account_id');
          //       let account =  obj.children.find(item=>{
          //         return item.id==obj.current_account_id
          //       })
          //       console.log(account,'vvvvvvvvvvvvvv');
          //       return account.data
          //     }else{
          //       return null
          //     }

          //   }else{
          //     return null
          //   }

          // })
          const formRef = reactive({
              title: "",
              avatar: "",
              publishType:1,
              is_private:0,//0公开  1自己可见
              time:'',
          });
  // 上传图片
          const handleUploadChange = (info) => {
              let resFileList = [...info.fileList];
              if (resFileList.length) {
                  resFileList.map((file, index) => {
                      if (file.response) {
                          if (file.response.code == 1000) {
                              file.url = file.response.data.fileUrl;
                          } else {
                              message.warning(file.response.msg);
                              resFileList.splice(index, 1);
                          }
                      }
                  });
              }
              state.fileList = resFileList;
              if (state.fileList.length) {
                  formRef.avatar = state.fileList[0].url;
              } else {
                  formRef.avatar = "";
              }
          };
      const onClose = () => {
       
        context.emit("onClose");
      };
  
      const getList = () => {
        request
          .get("/work_ai", "/user/team/app/chat/history", {
            chat_id: props.chatId,
          })
          .then((res) => {
            if (res.data) {
              state.list = res.data;
            }
          });
      };
  
      const init = () => {
      
        if (props.chatId) {
          getList();
        }
      };
  
      watch(
        () => props.visible,
        (val) => {
          if (val) {
            init();
          } else {
            state.list = [];
            state.noData = false;
          }
        }
      );
       
      
        const tab_under_list = computed(()=>{
          return state.groupAccountList.find(item=>item.key==state.currentTabId)?.sub??[]
        })
 
      
      const chooseAccont = ()=>{
        // getGroupAccountList()
        // if(Object.keys(state.confrim_tabs_accounts_obj).length){
        //   state.tabs_accounts_obj = JSON.parse(JSON.stringify(state.confrim_tabs_accounts_obj))
        // }
        // for(let key in state.tabs_accounts_obj){
        //   if(state.confrim_tabs_accounts_obj[key]){
        //     state.tabs_accounts_obj[key].checkedAccountIds = JSON.parse(JSON.stringify(state.confrim_tabs_accounts_obj[key].checkedAccountIds))
        //   }else{
        //     state.tabs_accounts_obj[key].checkedAccountIds = []
        //   }
        // }
        // state.currentTabId = state.active_memory_tab

        state.accountVisible = true
        
      }
      const memoryTabChange = (tab)=>{
        state.active_memory_tab = tab
      }
      
      const confirmChoose = ()=>{
      
        state.confrim_tabs_accounts_obj = JSON.parse(JSON.stringify(state.tabs_accounts_obj)) 
        state.accountVisible = false
        state.memory_tab_accounts_obj = JSON.parse(JSON.stringify(state.confrim_tabs_accounts_obj))

       
        
      }

      const getCheckedAccountClass = (id)=>{
        return state.memory_tab_accounts_obj[state.active_memory_tab].current_account_id ==id?'active-account':''
      }
      const chooseAccounts = computed(()=>{
        let accounts = []
        if( state.active_memory_tab){
            let obj = state.memory_tab_accounts_obj[ state.active_memory_tab]

            accounts = obj? obj.children.filter(item=>{
              return obj.checkedAccountIds.includes(item.id)
            }):[]

        }
       
        return accounts
      })
      
      const delAllChooseAccount = (key)=>{
        state.memory_tab_accounts_obj[key].checkedAccountIds = []
        state.confrim_tabs_accounts_obj[key].checkedAccountIds = []
        nextTick(()=>{
          let active_tab = ''
        for(let key in state.memory_tab_accounts_obj){
          if(state.memory_tab_accounts_obj[key].checkedAccountIds.length){
            active_tab = key
         
            break
          }
        }
     
        if(!active_tab){
          state.active_memory_tab = ''
        }else{
          state.active_memory_tab = active_tab
        }
        })
         
      }
      const delChooseAccount = (id)=>{
        for(let key in  state.confrim_tabs_accounts_obj){
          state.confrim_tabs_accounts_obj[key].children.map((item,index)=>{
            if(item.id==id){
              state.confrim_tabs_accounts_obj[key].checkedAccountIds.splice(state.confrim_tabs_accounts_obj[key].checkedAccountIds.indexOf(id),1)
            } 
          })
       
        }
      }

      const ok = (obj)=>{
        state.accountVisible = false
        state.memory_tab_accounts_obj = obj
        if(!state.active_memory_tab){
          // 处理初次默认选中分组
          for(let key in state.memory_tab_accounts_obj){
            let obj = state.memory_tab_accounts_obj[key]
          if(obj.checkedAccountIds.length){
            state.active_memory_tab = key
            // 处理初次默认选中分组下的账号
            if(!obj.current_account_id){
              obj.current_account_id = obj.checkedAccountIds.length?obj.checkedAccountIds[0]:''
            }
            break
          }
         }

        }
      }
      const submit = ()=>{
         // 去除所有 HTML 标签
        const strippedText = props.content.replace(/<[^>]+>/g, '');
        if(strippedText.trim().length === 0){
            return message.warning('请填写文章内容')
          }
          if(strippedText.trim().length >1000){
            return message.warning('文章内容长度不能大于1000')
          }
        if(chooseAccounts.value.length==0){
            return message.warning('请选择账号')
          }
          if(!formRef.title){
            return message.warning('请填写标题')
          }
          if(!formRef.avatar){
            return message.warning('请上传封面')
          }
          
          if(formRef.publishType==2&&!state.publishTime){
            return message.warning('请选择定时时间')
          }
          let account_id = chooseAccounts.value.map(item=>item.id)
        let params = {
             org_id:utils.getOrgId(),
             account_id,
             title:formRef.title,
             desc:props.content,
             cover_img: formRef.avatar,
             is_private:formRef.is_private,
            }
            if(formRef.publishType==2){
              params.fix_at =  state.publishTime
            }
           
            request.post("/work_ai", "/org/platform/account/article/add", params).then((res) => {
              context.emit('onClose')  
              message.success('发布成功')
              state.confrim_tabs_accounts_obj = {}
            
              formRef.title = ''
              formRef.avatar = ''
              formRef.is_private = 0
              formRef.publishType = 1
              formRef.publishTime = ''
              state.fileList = []
            });
      }
      const onTimeChange = (e)=>{
       
        state.publishTime = moment(e).format('YYYY-MM-DD HH:mm')
      }
      const allCheckedChange = (e)=>{
       
        if(e.target.checked){
          state.tabs_accounts_obj[state.currentTabId].checkedAccountIds =  state.tabs_accounts_obj[state.currentTabId].children.map(item=>item.id) 
        }else{
          state.tabs_accounts_obj[state.currentTabId].checkedAccountIds = []
        }
      }

      const checkedChange = (id)=>{
      
      if(state.tabs_accounts_obj[state.currentTabId].checkedAccountIds.includes(id)){
        state.tabs_accounts_obj[state.currentTabId].checkedAccountIds.splice(state.tabs_accounts_obj[state.currentTabId].checkedAccountIds.indexOf(id),1);
      }else{
        state.tabs_accounts_obj[state.currentTabId].checkedAccountIds.push(id);
      }
     
     }
     const openPage = ()=>{
      let url = `${
        utils.isEnv() ? "http://localhost:4022" : defaultSetting.requestDomain
      }`;
      let link = url + `/#/accountCenter`;
      window.open(link, "_blank");
     }
     const tabChange = (key)=>{
        state.currentTabId = key;
     }
      return {
        ...toRefs(state),
        formRef,
        onClose,
        handleUploadChange,
        checkedChange,
        chooseAccont,
        confirmChoose,
        chooseAccounts,
        delChooseAccount,
        onTimeChange,
        moment,
        submit,
        allCheckedChange,
        tab_under_list,
        openPage,
        tabChange,
        delAllChooseAccount,
        memoryTabChange,
        ok,
        getCheckedAccountClass,
    
      
      
      };
    },
  });
  </script>
  
  <style lang="less" scoped>
  .list-wrap{
    height: calc(100% - 55px);
    display: flex;
    width: 100%;
   
  }
    .footer{
        display: flex;
        justify-content: flex-end;
        width: 100%;
        align-items: center;
        border-top: 1px solid #e5e5e5;
        height: 55px;
        background-color: #fff;
    }
    .left-area{
        width: 120px;
        border-right: 1px solid #eee;
        padding: 20px 0;
    }
    .right-area{
        flex: 1;
        padding: 20px;
        height: 100%;
        overflow-y: auto;
    }
    .left-header{
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      color: rgb(255, 101, 98);
      
    }
    .text-20{
        font-size: 20px;
    }
    .add-btn{
      font-size: 20px;
      cursor: pointer;
      color: rgb(255, 101, 98);
      margin-left: 10px;
    }
    .accout-item{
      display: flex;
      align-items: center;
      height: 60px;
      border-bottom: 1px solid #eee;
      
    }
    .account-lable-item{
      cursor: pointer;
    }
    .account-avatar{
      width: 24px;
      height: 24px;
      border-radius: 50%;
      overflow: hidden;
      margin: 0 5px;
      object-fit: contain;
    }
    .choose-list{
      display: flex;
      flex-wrap: wrap;
      align-items: center;
    }
    .choose-item{
      position: relative;
      display: flex;
      align-items: center;
      margin: 5px;
    }
    .choose-item:hover .choose-item-close{
      visibility: visible!important;
    }
    .account-avatar-wrapper{
      display: flex;
      justify-content: center;
      align-items: center;
      width: 36px;
      height: 36px;
      border: 1px solid #e5e5e5;
      border-radius: 50%;
    }
    .choose-item-close{
      position: absolute;
      right: -10px;
      top: -10px;
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background-color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      visibility: hidden;
    }
    .left-list{

    }
    .left-item{
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 15px 0;
      padding: 10px 0;
      
      cursor: pointer;
      .choose-item-close{
      position: absolute;
      right: 15px;
      top: 0px;
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background-color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      visibility: hidden;
      }
     
      &:hover .choose-item-close{
        visibility: visible!important;
      }
      &:hover .choose-item-close{
        visibility: visible!important;
      }
    }
    .active_memory_tab:hover .choose-item-close{
      background-color: #e7e5f3;
    }
    .active_memory_tab{
        background-color: #e7e5f3!important;
      }
    .left-item-img{
      width: 40px;
      height: 40px;
      object-fit: contain;
    }
    .account-list{
      height: 450px;
      width: calc(100% - 200px);
      width: 100%;
      overflow-y: auto;
      margin-left: 20px;
    }
    .account-list-empty{
      width: 100%;
      height: 450px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .list-wrapper{
      display: flex;

      height: 450px;
    }
    .list-left{
      flex-shrink: 0;
      width: 199px;
      border-right: 1px solid #e5e5e5;
    }
    .tab-item{
      display: flex;
      justify-content: center;
      align-items: center;
      height: 45px;
   
      cursor: pointer;
      font-size: 14px;
      color: #333;
      font-weight: 500;
      padding: 0 10px;
      height: 50px;
    }
    .tab-active{
      background-color: #e7e5f3;
    }
    .tab-img{
      width: 30px;
      height: 30px;
      border-radius: 50%;
      object-fit: contain;
      margin-right: 10px;
    }
    .active-account{
      border:1px solid red;
    }
  </style>
  